<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-breadcrumb v-if="$route.query.id" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ $route.query.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        </el-breadcrumb>
        <hr v-if="$route.query.id" class="hr">
        <el-form ref="tagsFormRef" :inline="true" :model="tagsForm" label-width="80px">
          <el-form-item label="标签名称" prop="tagName">
            <el-input v-model="tagsForm.tagName" size="small" />
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-select v-model="tagsForm.state" size="small" placeholder="请选择">
              <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="cancelSubmit">清除</el-button>
            <el-button size="small" type="primary" @click="onSubmit">搜索</el-button>
          </el-form-item>
          <el-button size="small" type="success" icon="el-icon-edit" class="addBtn" @click="addTags">新增标签</el-button>
          <el-page-header v-if="$route.query.id" title="返回学科" class="el-page-header" @back="$router.back()" />
        </el-form>
        <el-alert
          :title="cTitle"
          :closable="false"
          type="info"
          show-icon
        />
        <el-table
          :data="tagsList"
          style="width: 100%"
          class="table"
        >
          <el-table-column
            type="index"
            label="序号"
            width="180"
          />
          <el-table-column
            prop="subjectName"
            label="所有学科"
            width="180"
          />
          <el-table-column
            prop="tagName"
            label="标签名称"
          />
          <el-table-column
            prop="username"
            label="创建者"
          />
          <el-table-column
            prop="addDate"
            label="创建日期"
          >
            <template slot-scope="scope">
              {{ transTime(scope.row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="state"
            label="状态"
          >
            <template slot-scope="scope">
              {{ scope.row.state===0? "禁用":"启用" }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="togger(scope.row)">{{ scope.row.state===1? "禁用":"启用" }}</el-button>
              <el-button :disabled="scope.row.state===0" type="text" size="small" @click="editTags(scope.row)">修改</el-button>
              <el-button :disabled="scope.row.state===0" type="text" size="small" @click="delTags(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          class="pagination"
          :current-page="query.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="query.pagesize"
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-dialog
          :title="isEdit? '修改目录':'新增目录'"
          :visible.sync="isShowDialog"
          width="20%"
        >
          <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules" label-width="80px">
            <el-form-item v-if="!$route.query.id" label="所属学科" prop="subjectID">
              <el-select v-model="dialogForm.subjectID" placeholder="请选择" style="width:260px">
                <el-option v-for="item in allSubject" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录名称" prop="tagName">
              <el-input v-model="dialogForm.tagName" placeholder="请输入目录名称" style="width:260px" />
            </el-form-item>
            <el-form-item class="diaBtn">
              <el-button @click="cancelAddOrEditSubmit">取消</el-button>
              <el-button type="primary" @click="addOrEditSubmit">确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list, detail, add, update, remove } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
import { status } from '@/api/hmmm/constants'

export default {
  name: 'Tags',
  data () {
    return {
      row: {},
      dialogRules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'blur' }
        ],
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ]
      },
      tagsForm: {
        tagName: '',
        state: null
      },
      allSubject: [
        {
          value: 0,
          label: ''
        }
      ],
      tagsList: [],
      query: {
        page: 1,
        pagesize: 10
      },
      total: 20,
      isShowDialog: false,
      dialogForm: {
        subjectID: null,
        tagName: ''
      },
      status,
      isEdit: false,
      isDisabled: false
    }
  },

  computed: {
    cTitle () {
      return `数据一共${this.total}条`
    }
  },

  watch: {
    '$route.query': async function () {
      if (this.$route.query.id) {
        this.getSubjectsToTagsList()
      } else {
        this.getTagsList()
      }
    }
  },

  created () {
    // this.getTagsList()
    this.getAllSubject()
    this.toggersList()
  },
  methods: {
    toggersList () {
      if (this.$route.query.id) {
        this.getSubjectsToTagsList()
      } else {
        this.getTagsList()
      }
    },

    async getAllSubject () {
      const res = await simple()
      this.allSubject = res.data
    },

    async togger (row) {
      if (row.state === 1) {
        row.state = 0
        this.isDisabled = false
      } else {
        row.state = 1
        this.isDisabled = true
      }
    },

    transTime (time) {
      const newTime = this.dayjs(time).format('YYYY-MM-DD HH:mm:ss')
      return newTime
    },

    async delTags (row) {
      const confirmRes = await this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message('已取消删除')
      if (this.tagsList.length === 1) {
        this.query.page--
        if (this.query.page < 1) {
          this.query.page = 1
        }
      }
      await remove(row)
      this.$message.success('删除成功')
      this.isShowDialog = false
      this.toggersList()
    },

    // 数据回显
    async editTags (row) {
      this.row = row
      this.isShowDialog = true
      this.isEdit = true
      const res = await detail(row)
      this.dialogForm = res.data
    },

    resetDialogForm () {
      this.$refs.dialogFormRef.resetFields()
    },

    cancelAddOrEditSubmit () {
      this.resetDialogForm()
      this.isShowDialog = false
    },

    async addOrEditSubmit () {
      this.$refs.dialogFormRef.validate(async valid => {
        if (!valid) return
        if (this.isEdit) {
          if (this.$route.query.id) {
            this.dialogForm.subjectID = Number(this.$route.query.id)
            await update({ ...this.row, tagName: this.dialogForm.tagName })
            this.getSubjectsToTagsList()
          } else {
            await update(this.dialogForm)
            this.getTagsList()
          }
          this.$message.success('修改目录成功')
          this.isShowDialog = false
        } else {
          if (this.$route.query.id) {
            this.dialogForm.subjectID = Number(this.$route.query.id)
            await add(this.dialogForm)
            this.query.page = 1
            this.getSubjectsToTagsList()
          } else {
            await add(this.dialogForm)
            this.query.page = 1
            this.getTagsList()
          }
          this.$message.success('添加目录成功')
          this.isShowDialog = false
        }
        this.resetDialogForm()
      })
    },

    addTags () {
      this.isShowDialog = true
      this.isEdit = false
    },

    async getTagsList () {
      const { data: res } = await list({ ...this.query })
      this.tagsList = res.items
      this.total = res.counts
    },

    async getSubjectsToTagsList () {
      if (this.$route.query.id) {
        this.dialogForm.subjectID = Number(this.$route.query.id)
        const { data: res } = await list({ subjectID: this.dialogForm.subjectID, ...this.query })
        this.tagsList = res.items
        this.total = res.counts
      }
    },

    handleSizeChange (newPagesize) {
      this.query.pagesize = newPagesize
      // this.getTagsList()
      this.toggersList()
    },

    handleCurrentChange (newPage) {
      this.query.page = newPage
      // this.getTagsList()
      this.toggersList()
    },

    cancelSubmit () {
      this.resetTagsForm()
    },

    onSubmit () {
      this.$refs.tagsFormRef.validate(valid => {
        if (!valid) return
        const newTagsForm = this.tagsList.filter(item => {
          return item.tagName === this.tagsForm.tagName && item.state === this.tagsForm.state
        })
        this.tagsList = newTagsForm
        this.query.page = 1
        this.resetTagsForm()
      })
    },

    resetTagsForm () {
      this.$refs.tagsFormRef.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.hr {
 margin-top: 15px;
}
.el-page-header {
display: inline;
float: right;
margin-top: 5px;
border-right: none;
color: #66b1ff;
}
.app-container {
    padding: 10px;
}
.addBtn {
float: right;
}
.diaBtn {
  display: flex;
  justify-content: flex-end;
}
.table {
 margin-top: 15px;
}
.pagination {
float: right;
margin: 20px 0;
}
</style>
